package com.cw.jeeyt.controller.process;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.StringUtils;
import com.cw.jeeyt.common.process.Flow;
import com.cw.jeeyt.common.utils.process.FlowableUtils;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.core.util.SessionUtil;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.jeeyt.service.impl.process.ReProcDefService;
import com.cw.jeeyt.service.intf.process.FlowTaskService;
import com.cw.lang.common.config.Global;
import com.cw.lang.common.utils.GsonUtil;

/**
 * 流程个人任务相关Controller
 * * @author liuruijun
 *
 * @version 2017-11-03
 */
@Controller
@RequestMapping(value = "/act/task")
public class FlowTaskController extends BaseController {

    @Autowired
    private FlowTaskService actTaskService;

    @Autowired
    private ReProcDefService reProcDefService;

    /**
     * 获取待办列表
     *
     * @return
     */
    @RequestMapping("todo")
    public String todoList(Model model) {
        model.addAttribute("permission", new PermissionDirective());
        model.addAttribute("PageDict", new PageDictDirective());
        return "process/processTaskTodoList";
    }

    @ResponseBody
    @RequestMapping("todoData")
    public ResultData todoData(@RequestBody DataTable dataTable, Flow act) {
        ResultData resultData = actTaskService.todoList(dataTable, act);
        resultData.setDraw(dataTable.getDraw());
        return resultData;
    }

    @RequestMapping("diagramViewer")
    public String diagramViewer(String definitionId, String instanceId, String hisInsId, Model model) {

        model.addAttribute("definitionId", StringUtils.isBlank(definitionId) ? "" : definitionId);
        model.addAttribute("instanceId", StringUtils.isBlank(instanceId) ? "" : instanceId);
        model.addAttribute("hisInsId", StringUtils.isBlank(hisInsId) ? "" : hisInsId);

        return "process/flowDiagramViewer";
    }

    /**
     * 获取已办任务
     *
     * @return
     */
    @RequestMapping("history")
    public String historicList(Model model) {
        model.addAttribute("permission", new PermissionDirective());
        model.addAttribute("PageDict", new PageDictDirective());
        return "process/processTaskHistoryList";
    }

    @ResponseBody
    @RequestMapping("historyData")
    public ResultData historicDataList(Flow act, @RequestBody DataTable dataTable) {
        return actTaskService.historicList(dataTable, act);
    }

    /**
     * 获取已发任务
     *
     * @return
     */
    @RequestMapping("hasSent")
    public String hasSentList(Model model) {
        model.addAttribute("permission", new PermissionDirective());
        model.addAttribute("PageDict", new PageDictDirective());
        return "process/processTaskHasSentList";
    }

    @ResponseBody
    @RequestMapping("hasSentData")
    public ResultData hasSentDataList(@RequestBody DataTable dataTable) {
        return actTaskService.hasSentList(dataTable);
    }

    /**
     * 获取流转历史列表
     *
     * @param act 流程实例
     * @param startAct 开始活动节点名称
     * @param endAct 结束活动节点名称
     */
    @RequestMapping("histoicFlow")
    public String histoicFlow(Flow act, String startAct, String endAct, Model model) {
        if (StringUtils.isNotBlank(act.getProcInsId())) {
            List<Flow> histoicFlowList = actTaskService.histoicFlowList(act.getProcInsId(), startAct, endAct);
            model.addAttribute("histoicFlowList", histoicFlowList);
        }
        return "process/flowTaskHistoricFlow";
    }

    /**
     * 获取流程表单
     *
     * @param act 工作流Entity
     */
    @RequestMapping("form")
    public String form(Flow act) {

        // 获取流程XML上的表单KEY
        String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());

        // 获取流程实例对象
        if (act.getProcInsId() != null) {
            ProcessInstance procIns = actTaskService.getProcIns(act.getProcInsId());
            if (procIns != null) {
                String[] ss = procIns.getBusinessKey()
                    .split(":");
                act.setBusinessTable(ss[0]);
                act.setBusinessId(ss[1]);
            } else {
                HistoricProcessInstance history = actTaskService.getHistoryProcIns(act.getProcInsId());
                String[] ss = history.getBusinessKey()
                    .split(":");
                act.setBusinessTable(ss[0]);
                act.setBusinessId(ss[1]);
            }
        }

        return "redirect:" + FlowableUtils.getFormUrl(formKey, act);
    }

    /**
     * 获取流程 发起流程列表
     */
    @RequestMapping("process")
    public String processList(Model model) {
        model.addAttribute("permission", new PermissionDirective());
        model.addAttribute("PageDict", new PageDictDirective());
        return "process/processTaskList";
    }

    /**
     * 获取流程列表
     *
     * @param category 流程分类
     * @param dataTable 流程分类
     */
    @RequestMapping("processDataList")
    @ResponseBody
    public ResultData processDataList(@RequestBody DataTable dataTable, String category, Model model) {
        return reProcDefService.processList(dataTable, category);
    }

    /**
     * 启动流程
     *
     * @param act FlowEntity
     */
    @RequestMapping("start")
    @ResponseBody
    public String start(Flow act) {
        actTaskService.startProcess(act.getProcDefKey(), act.getBusinessId(), act.getBusinessTable());
        return "true";
    }

    /**
     * 签收任务
     *
     * @param taskId 任务ID
     */
    @RequestMapping("claim")
    @ResponseBody
    public JsonResultDto claim(String taskId) {
        String userId = SessionUtil.getSessionUserId()
            .toString();
        actTaskService.claim(taskId, userId);
        JsonResultDto jsonResultDto = new JsonResultDto(false);
        jsonResultDto.setSuccess(true);
        jsonResultDto.setMsg("签收成功");
        return jsonResultDto;
    }

    /**
     * 完成任务
     *
     * @param act FlowEntity
     */
    @RequestMapping("complete")
    @ResponseBody
    public String complete(Flow act) {
        actTaskService.complete(act.getTaskId(), act.getProcInsId(), act.getComment(), act.getVars()
            .getVariableMap());
        return "true";
    }

    /**
     * 输出跟踪流程信息
     *
     * @param proInsId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("trace/info/{proInsId}")
    public List<Map<String, Object>> traceInfo(@PathVariable("proInsId") String proInsId) throws Exception {
        List<Map<String, Object>> activityInfos = actTaskService.traceProcess(proInsId);
        return activityInfos;
    }

    /**
     * 删除任务
     *
     * @param taskId 流程实例ID
     * @param reason 删除原因
     */
    @RequestMapping("deleteTask")
    @ResponseBody
    public String deleteTask(String taskId, String reason) {

        if (StringUtils.isBlank(reason)) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("result", Global.FALSE);
            resultMap.put("message", "删除失败，请填写删除原因！");
            return GsonUtil.objectToJsonString(resultMap);
        } else {
            actTaskService.deleteTask(taskId, reason);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result", Global.TRUE);
        resultMap.put("message", "删除任务成功，任务ID=" + taskId);
        return GsonUtil.objectToJsonString(resultMap);
    }
}
